import axios from 'axios'
//这里引用了element的loading全屏加载
import { ElLoading } from 'element-plus';
import { ElMessage } from 'element-plus'
import app_config from '@/config'
import store from "@/store"
import { router } from "@/router"

const service = axios.create({
    baseURL: app_config.BASE_URL,
    timeout: app_config.TIMEOUT // 设置请求超时时间
})
let loading = false;
let timer = null
let waiteList = ['/login', '/login_out']

function clear() {
    if (loading) {
        store.commit('appConfig/setLoading', false)
        loading = false
    }
    if (timer !== null) {
        clearTimeout(timer)
        timer = null
    }
}

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        // 处理登录问题
        if (store.state.user.token !== null) {
            config.headers['X-Token'] = store.state.user.token
        } else {
            router.push('/login')
        }

        // 处理加载动画
        if (config.showLoading !== false) {
            if (timer !== null) {
                clear()
            }
            timer = setTimeout(() => {
                loading = true
                store.commit('appConfig/setLoading', loading)
                timer = null
            }, app_config.REQUEST_LOADING_INTERVALS)
        }
        if (app_config.DEBUG) {
            console.log('-----发起请求-----', config);
        }
        return config
    },
    (error) => {
        clear()
        // 发送失败
        if (config.DEBUG) {
            console.warn('-----发起请求错误-----', error);
        }
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        clear()
        if (app_config.DEBUG) {
            console.log('-----得到响应-----', response);
        }
        if (response.code === 401) {
            router.push('/login')
        }
        return response.data
    },
    (error) => {
        if (app_config.DEBUG) {
            console.warn('-----得到响应错误-----', error.response.code, error.response);
        }
        clear()
        if (error.response) {
            return Promise.reject(error.response)
        } else {
            ElMessage.error({
                duration: 3000,
                message: `发生错误：${error.message}`
            })
        }
    }
)

export default service